const _dbCached = {}

export function get(key, default_value = null) {
  let value = _dbCached[key]
  if (!value) {
    value = localStorage.getItem(key)
    if (value) {
      value = JSON.parse(value)
    }
    _dbCached[key] = value
  }
  if (value === undefined || value === null) {
    value = default_value
  }
  return value
}

export function set(key, value) {
  if (value === undefined || value === null) {
    remove(key)
    return
  }
  _dbCached[key] = value
  localStorage.setItem(key, JSON.stringify(value))
}

export function getField(key, field, defaultValue) {
  const item = get(key) || {}
  if (field in item) {
    return item[field]
  }
  return defaultValue
}

export function setField(key, field, value) {
  const item = get(key) || {}
  item[field] = value
  set(key, item)
}

export function remove(key) {
  delete _dbCached[key]
  localStorage.removeItem(key)
}
